﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace Ivan.Dm.ChromeRemoteDebugger.Protocol {
    public static class JsonHelper {
        public static string Serialize<T>(T objectInstance) {
            var serializer = new DataContractJsonSerializer(typeof(T));
            string serializedObject = string.Empty;
            using (var stream = new MemoryStream()) {
                serializer.WriteObject(stream, objectInstance);
                serializedObject = ASCIIEncoding.ASCII.GetString(stream.ToArray());
            }
            return serializedObject;
        }

        public static T Deserialize<T>(string serializedObject) {
            T objectInstance = default(T);
            var serializer = new DataContractJsonSerializer(typeof(T));
            byte[] serializedObjectBytes = ASCIIEncoding.ASCII.GetBytes(serializedObject);
            using (var stream = new MemoryStream(serializedObjectBytes)) {
                objectInstance = (T)serializer.ReadObject(stream);
            }
            return objectInstance;
        }
    }
}
